package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.domain.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置数据的业务实现类
 */
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 预约数据的批量添加或修改
     *
     * @param orderSettings
     */
    @Transactional
    @Override
    public void addOrUpdateBatchOrderSetting(List<OrderSetting> orderSettings) {
        if (ObjectUtils.isEmpty(orderSettings)) {
            throw new RuntimeException("数据为空");
        }
        for (OrderSetting orderSetting : orderSettings) {
            if (orderSetting.getOrderDate() == null || orderSetting.getNumber() < 1) {
                throw new RuntimeException("关键数据不能为空");
            }
            Integer count = orderSettingDao.selectCountByDate(orderSetting.getOrderDate());
            if (count > 0) {
                orderSettingDao.updateNumberByDate(orderSetting);
            } else {
                orderSettingDao.insertBatchOrderSetting(orderSetting);
            }
        }
    }


    /**
     * 根据年月查询这个月的预约数据
     *
     * @param time
     * @return
     */
    @Override
    public List<Map<String, String>> findOrderSettingByDate(String time) {
        String beginDate = time + "-1";
        String endDate = time + "-31";
        return orderSettingDao.findOrderSettingByDate(beginDate, endDate);
    }

    /**
     * 根据日期修改或者设置单个预约数据
     *
     * @param dateString
     * @param number
     */
    @Transactional
    @Override
    public void addOrUpdateOrderSetting(String dateString, Integer number) {
        try {
            if (ObjectUtils.isEmpty(number) || StringUtils.isEmpty(dateString)) {
                throw new RuntimeException("关键数据不能为空");
            }
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);
            Integer count = orderSettingDao.selectCountByDate(date);
            OrderSetting orderSetting = new OrderSetting(date, number);
            if (count > 0) {
                orderSettingDao.updateNumberByDate(orderSetting);
            } else {
                orderSettingDao.insertBatchOrderSetting(orderSetting);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
